package com.tools;

import java.io.InputStream;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class ImageManager {
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午10:38:23
	 * @param context
	 * @param bitmapName
	 * @return
	 * @TODO 从内存中取图片,如果内存中没有图片，则从ASS中取出
	 ***********************************************************/
	private  static HashMap<String, Bitmap>	bitmap_list	= new HashMap<String, Bitmap>();
	private  static HashMap<String, Drawable>	drawable_list	= new HashMap<String, Drawable>();
	
	public static Bitmap getBitmap(Context context, String bitmapName) {
		Bitmap bitmap = bitmap_list.get(bitmapName);
		if (bitmap == null) {
			bitmap = getBitmapFormAss(context, bitmapName);
			bitmap_list.put(bitmapName, bitmap);
		}
		return bitmap;
	}
	
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午10:38:10
	 * @param context
	 * @param fileName
	 * @return
	 * @TODO 从ASS中取图片
	 ***********************************************************/
	public  static Bitmap getBitmapFormAss(Context context, String fileName) {
		InputStream is = null;
		try {
			is = context.getAssets().open(fileName);
			if (is == null) throw new NullPointerException("file path is error");
			return BitmapFactory.decodeStream(is);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午10:42:56
	 * @param bitmapName
	 *            图片名
	 * @TODO 从内存中删除指定名图片
	 ***********************************************************/
	public static  void destroyBitmap(String bitmapName) {
		bitmap_list.remove(bitmapName);
	}
	
	public static Drawable getDrawable(Context context,String fileName){
		Drawable drawable = drawable_list.get(fileName);
		if (drawable == null) {
			try {
				InputStream is = context.getAssets().open(fileName);
				drawable = Drawable.createFromStream(is, "src");
				drawable_list.put(fileName, drawable);
			} catch (Exception e) {
				Log.e("", "open assets "+fileName+" is error");
				e.printStackTrace();
			}
		}
		return drawable;
	}
}
